<script setup>
import { ref, onMounted } from 'vue'

const board = ref([])
const score = ref(0)
const gameOver = ref(false)
const boardSize = 4

// 初始化游戏板
const initBoard = () => {
  board.value = Array(boardSize).fill().map(() => Array(boardSize).fill(0))
  score.value = 0
  gameOver.value = false
  addNewTile()
  addNewTile()
}

// 添加新的数字块
const addNewTile = () => {
  const emptyCells = []
  for (let i = 0; i < boardSize; i++) {
    for (let j = 0; j < boardSize; j++) {
      if (board.value[i][j] === 0) {
        emptyCells.push({ x: i, y: j })
      }
    }
  }
  
  if (emptyCells.length > 0) {
    const randomCell = emptyCells[Math.floor(Math.random() * emptyCells.length)]
    board.value[randomCell.x][randomCell.y] = Math.random() < 0.9 ? 2 : 4
  }
}

// 检查游戏是否结束
const checkGameOver = () => {
  // 检查是否有空格
  for (let i = 0; i < boardSize; i++) {
    for (let j = 0; j < boardSize; j++) {
      if (board.value[i][j] === 0) return false
    }
  }
  
  // 检查是否有可合并的相邻数字
  for (let i = 0; i < boardSize; i++) {
    for (let j = 0; j < boardSize; j++) {
      if (i < boardSize - 1 && board.value[i][j] === board.value[i + 1][j]) return false
      if (j < boardSize - 1 && board.value[i][j] === board.value[i][j + 1]) return false
    }
  }
  
  return true
}

// 移动和合并数字
const moveTiles = (direction) => {
  const originalBoard = JSON.stringify(board.value)
  let moved = false
  
  const moveLeft = () => {
    for (let i = 0; i < boardSize; i++) {
      let row = board.value[i].filter(cell => cell !== 0)
      for (let j = 0; j < row.length - 1; j++) {
        if (row[j] === row[j + 1]) {
          row[j] *= 2
          score.value += row[j]
          row.splice(j + 1, 1)
        }
      }
      while (row.length < boardSize) row.push(0)
      if (JSON.stringify(board.value[i]) !== JSON.stringify(row)) moved = true
      board.value[i] = row
    }
  }

  const rotate = () => {
    const newBoard = Array(boardSize).fill().map(() => Array(boardSize).fill(0))
    for (let i = 0; i < boardSize; i++) {
      for (let j = 0; j < boardSize; j++) {
        newBoard[i][j] = board.value[j][boardSize - 1 - i]
      }
    }
    board.value = newBoard
  }

  // 根据方向旋转板子
  if (direction === 'up') rotate()
  if (direction === 'right') { rotate(); rotate() }
  if (direction === 'down') { rotate(); rotate(); rotate() }

  moveLeft()

  // 旋转回原来的方向
  if (direction === 'up') { rotate(); rotate(); rotate() }
  if (direction === 'right') { rotate(); rotate() }
  if (direction === 'down') rotate()

  if (moved) {
    addNewTile()
    if (checkGameOver()) {
      gameOver.value = true
    }
  }
}

// 处理键盘事件
const handleKeydown = (event) => {
  if (gameOver.value) return
  
  switch (event.key) {
    case 'ArrowLeft':
      moveTiles('left')
      break
    case 'ArrowRight':
      moveTiles('right')
      break
    case 'ArrowUp':
      moveTiles('up')
      break
    case 'ArrowDown':
      moveTiles('down')
      break
  }
}

onMounted(() => {
  initBoard()
  window.addEventListener('keydown', handleKeydown)
})

const getTileColor = (value) => {
  const colors = {
    2: '#eee4da',
    4: '#ede0c8',
    8: '#f2b179',
    16: '#f59563',
    32: '#f67c5f',
    64: '#f65e3b',
    128: '#edcf72',
    256: '#edcc61',
    512: '#edc850',
    1024: '#edc53f',
    2048: '#edc22e'
  }
  return colors[value] || '#cdc1b4'
}

const getTileTextColor = (value) => {
  return value <= 4 ? '#776e65' : '#f9f6f2'
}
</script>

<template>
  <div class="game-2048">
    <h1>2048</h1>
    <div class="score-container">
      分数: {{ score }}
    </div>
    <button class="restart-btn" @click="initBoard">重新开始</button>
    
    <div class="game-board">
      <div v-for="(row, i) in board" :key="i" class="row">
        <div 
          v-for="(cell, j) in row" 
          :key="j" 
          class="cell"
          :style="{
            backgroundColor: getTileColor(cell),
            color: getTileTextColor(cell)
          }"
        >
          {{ cell || '' }}
        </div>
      </div>
    </div>
    
    <div v-if="gameOver" class="game-over">
      游戏结束!
      <button @click="initBoard">再来一局</button>
    </div>
  </div>
</template>

<style scoped>
.game-2048 {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.score-container {
  font-size: 24px;
  margin: 10px 0;
}

.restart-btn {
  padding: 10px 20px;
  font-size: 16px;
  margin: 10px 0;
  background-color: #8f7a66;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.game-board {
  background: #bbada0;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.row {
  display: flex;
}

.cell {
  width: 80px;
  height: 80px;
  margin: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: bold;
  border-radius: 4px;
  transition: all 0.15s ease;
}

.game-over {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(238, 228, 218, 0.73);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 48px;
  color: #776e65;
}

.game-over button {
  margin-top: 20px;
  padding: 10px 20px;
  font-size: 20px;
  background-color: #8f7a66;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style> 